import React, { FC } from 'react';
import { FormPanel, FormPanelType, InputType, type FormPanelObject, FormPanelBtnAlign, Utils } from 'lfun-bg-comp';
import { Breadcrumb, Button, Table, TableProps, Space } from 'antd';
import _ from 'lodash';
import { useNavigate, useLocation } from 'react-router-dom';
import { PageContainer } from '@/component/page-container';
import { KG_LEVEL, FOUNDER_TYPE, SCHOOL_OPERATION_TYPE } from '@/constant/schoolOptions';
import { PAGINATIONCONFIG } from '@/constant/page';
import utils, { buildPageItemTxtByEduType, getPagePath, getPathRoot, get_stoge_pz, set_stoge_pz } from '@/utils';
import styles from './index.less';
import { SearchPlanningSchool, getPlanningSchoolAudit } from '@/service/unit/planning';
import { APPROVAL_STATUS } from '@/constant';
import PermissionButton, { isPermissionOperate } from '@/component/permission-button';
import useCountry from '@/hooks/useCountry';

const Groups: FC = () => {
  const [dataSource, setDataSource] = React.useState([]);
  const [total, setTotal] = React.useState(0);
  const [pageSize, setPageSize] = React.useState(get_stoge_pz());
  const [pageIndex, setPageIndex] = React.useState(1);
  const [form, setForm] = React.useState(null);
  const [tableLoading, setTableLoading] = React.useState(false);
  const navigate = useNavigate();
  const location = useLocation();
  const country = useCountry();
  const searchTemplate: FormPanelType[] = [
    {
      title: '',
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
      inputs: [
        {
          label: buildPageItemTxtByEduType('园所名称'),
          name: 'planning_school_name',
          key: 'planning_school_name',
          textRange: [0, 20],
        },
        {
          label: '举办者类型',
          name: 'founder_type',
          key: 'founder_type',
          inputType: InputType.cascader,
          renderOption: FOUNDER_TYPE,
          inputProps: {
            multiple: true,
          },
        },
        {
          label: '行政管辖区',
          name: 'borough',
          key: 'borough',
          inputType: InputType.select,
          renderOption: country,
        },
        {
          label: '地域管辖区',
          name: 'block',
          key: 'block',
          inputType: InputType.select,
          renderOption: country,
        },
        {
          label: '状态',
          name: 'appoval_status',
          key: 'appoval_status',
          inputType: InputType.select,
          renderOption: APPROVAL_STATUS,
        },
        //   {
        //     label: '状态',
        //     name: 'status',
        //     key: 'status',
        //     inputType: InputType.select,
        //     renderOption: KG_ORDER_STATUS,
        //   },
        {
          label: buildPageItemTxtByEduType('园所代码'),
          name: 'planning_school_code',
          key: 'planning_school_code',
          inputType: InputType.text,
          textRange: [0, 20],
        },
        {
          label: '星级',
          name: 'planning_school_level',
          key: 'planning_school_level',
          inputType: InputType.select,
          hidden: Utils.getProps('edu_type') !== 'kg',
          renderOption: KG_LEVEL,
        },
      ],
    },
  ];
  const columns: TableProps['columns'] = [
    {
      title: '编号',
      width: 100,
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      fixed: 'left',
      render(val, row, index) {
        return index + 1;
      },
    },
    {
      title: buildPageItemTxtByEduType('园所代码'),
      width: 100,
      dataIndex: 'planning_school_no',
      key: 'planning_school_no',
      align: 'center',
      fixed: 'left',
    },
    {
      title: buildPageItemTxtByEduType('园所名称(学校)'),
      width: 500,
      dataIndex: 'planning_school_name',
      key: 'planning_school_name',
      align: 'center',
      fixed: 'left',
    },
    {
      title: '行政管辖区',
      width: 150,
      dataIndex: 'borough',
      key: 'borough',
      align: 'center',
      render: (text: any) => {
        return _.find(country, { value: String(text) })?.label;
      },
    },
    {
      title: '地域管辖区',
      width: 150,
      dataIndex: 'block',
      key: 'block',
      align: 'center',
      render: (text: any) => {
        return _.find(country, { value: String(text) })?.label;
      },
    },
    {
      title: '举办者类型',
      width: 300,
      dataIndex: 'founder_type',
      key: 'founder_type',
      align: 'center',
      render: (text: any) => {
        const arr: any[] = [];
        if (_.isArray(text)) {
          text.forEach(v => {
            const label = utils.findLabelDeep(FOUNDER_TYPE, String(v));
            if (label) {
              arr.push(label);
            }
          });
        }
        return arr.join('/');
      },
    },
    {
      title: buildPageItemTxtByEduType('园所星级'),
      dataIndex: 'planning_school_level',
      key: 'planning_school_level',
      align: 'center',
      width: 100,
      render: (text: any) => {
        return _.find(KG_LEVEL, { value: String(text) })?.label;
      },
    },
    {
      title: '教育层次',
      dataIndex: 'planning_school_edu_level',
      key: 'planning_school_edu_level',
      align: 'center',
      width: 100,
      render: (text: any) => {
        return _.find(SCHOOL_OPERATION_TYPE, { value: String(text) })?.label;
      },
    },
    {
      title: '学校（机构）类别',
      dataIndex: 'planning_school_category',
      key: 'planning_school_category',
      align: 'center',
      width: 200,
      render: (text: any, record: any) => {
        const res = _.find(SCHOOL_OPERATION_TYPE, { value: record.planning_school_edu_level });
        if (res) {
          return _.find(res.children, { value: String(text) })?.label;
        }
        return text;
      },
    },
    {
      title: '办学类型',
      dataIndex: 'planning_school_operation_type',
      key: 'planning_school_operation_type',
      width: 100,
      align: 'center',
      render: (text: any, record: any) => {
        const edu_level_res = _.find(SCHOOL_OPERATION_TYPE, { value: record.planning_school_edu_level });
        if (edu_level_res) {
          const res = _.find(edu_level_res.children, { value: String(record.planning_school_category) });
          if (res) {
            return _.find(res.children, { value: String(text) })?.label;
          }
        }
        return text;
      },
    },
    {
      title: '办学类型',
      dataIndex: 'planning_school_operation_type',
      key: 'planning_school_operation_type',
      width: 100,
      align: 'center',
      render: (text: any) => {
        const arr: any[] = [];
        if (_.isArray(text)) {
          text.forEach(v => {
            const label = utils.findLabelDeep(SCHOOL_OPERATION_TYPE, String(v));
            if (label) {
              arr.push(label);
            }
          });
        }
        return arr.join('/');
      },
    },
    {
      title: '状态',
      dataIndex: 'approval_status',
      key: 'approval_status',
      width: 100,
      align: 'center',
      render: (text: any, record: any) => _.find(APPROVAL_STATUS, { value: String(text) })?.label,
    },
    {
      title: '审核说明',
      dataIndex: 'reason',
      key: 'reason',
      width: 200,
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'op',
      key: 'op',
      //width: 200,
      fixed: 'right',
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text, record) => {
        return (
          <Space>
            <PermissionButton permission="view">
              <Button
                key="look"
                type="link"
                size="small"
                onClick={() =>
                  navigate(
                    `${getPathRoot()}/planning-audit/${getProcess_path()}/details/${record.planning_school_id}`,
                    {
                      state: { ...record, code: 'view' },
                    }
                  )
                }
              >
                查看
              </Button>
            </PermissionButton>
            {['pending', 'progressing'].includes(record.approval_status) && (
              <PermissionButton permission="approval">
                <Button
                  type="link"
                  size="small"
                  onClick={() =>
                    navigate(
                      `${getPathRoot()}/planning-audit/${getProcess_path()}/details/${record.planning_school_id}`,
                      {
                        state: { ...record },
                      }
                    )
                  }
                >
                  审核
                </Button>
              </PermissionButton>
            )}
          </Space>
        );
      },
      align: 'center',
    },
  ];
  const getProcess_code = () => {
    const path = location.pathname;
    if (path.includes('planning-audit/openschool')) {
      return 'p_school_open';
    }
    if (path.includes('planning-audit/closeschool')) {
      return 'p_school_close';
    }
    if (path.includes('planning-audit/changekeyinfo')) {
      return 'p_school_keyinfo_change';
    }
    return '';
  };
  const getProcess_path = () => {
    return {
      p_school_open: 'openschool',
      p_school_close: 'closeschool',
      p_school_keyinfo_change: 'changekeyinfo',
    }[getProcess_code()];
  };
  const search = async (params: any, pageSize, pageIndex) => {
    if (tableLoading) {
      return;
    }
    setTableLoading(true);
    const searchParams: SearchPlanningSchool = {
      ...params,
      process_code: getProcess_code(),
    };
    if (params.founder_type && params.founder_type.length > 0) {
      const fouder_type_set1 = new Set<string>();
      const fouder_type_set2 = new Set<string>();
      const fouder_type_set3 = new Set<string>();
      params.founder_type.forEach(item => {
        if (item.length > 2) fouder_type_set3.add(item[2]);
        else if (item.length > 1) fouder_type_set2.add(item[1]);
        else if (item.length > 0) fouder_type_set1.add(item[0]);
      });
      searchParams.founder_type = Array.from(fouder_type_set1);
      searchParams.founder_type_lv2 = Array.from(fouder_type_set2);
      searchParams.founder_type_lv3 = Array.from(fouder_type_set3);
    }
    const { success, data } = await getPlanningSchoolAudit(searchParams, pageIndex, pageSize);
    if (success) {
      setDataSource(
        data?.items?.map((v, i) => {
          v.key = i;
          v.founder_type = [v.founder_type, v.founder_type_lv2, v.founder_type_lv3];
          // v.planning_school_operation_type = [
          //   v.planning_school_operation_type,
          //   v.planning_school_operation_type_lv2,
          //   v.planning_school_operation_type_lv3,
          // ];
          return v;
        })
      );
      setTotal(data.total);
      setPageSize(pageSize);
      setPageIndex(pageIndex);
      setTableLoading(false);
    }
  };

  const pageChange = (pageIndex, pageSize) => {
    set_stoge_pz(pageSize);
    search(form?.getFieldsValue(), pageSize, pageIndex);
  };

  React.useEffect(() => {
    if (form && form.resetFields) form.resetFields();
    search({}, pageSize, 1);
  }, [location.pathname]);

  return (
    <PageContainer header={<Breadcrumb items={[{ title: getPagePath().power_name }]} />}>
      <FormPanel
        template={searchTemplate}
        key={1}
        submitBtnText="搜索"
        restBtnText="重置"
        btnsAlign={FormPanelBtnAlign.right}
        onLoad={form => setForm(form)}
        onFinish={(formPanelObject: FormPanelObject) => {
          const params = formPanelObject.getFieldsValue();
          search(params, pageSize, 1);
          setForm(form);
          return false;
        }}
      />
      <Table
        className={styles.table}
        dataSource={dataSource}
        columns={
          Utils.getProps('edu_type') === 'kg' ? columns : columns.filter(it => it.key !== 'planning_school_level')
        }
        scroll={{ x: 'max-content' }}
        loading={tableLoading}
        pagination={{ ...PAGINATIONCONFIG, total, pageSize, current: pageIndex, onChange: pageChange }}
      />
    </PageContainer>
  );
};

export default Groups;
